﻿#include "BaseType.h"
#include "Socket.h"
#include "Thread.h"
#include "Tracer.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define UDP_PORT	(6062)		/* 定义服务器端口 */

class UdpServer : public UdpSocket, public Runnable{
public:
    bool initServer(int port)
    {
        if(m_serverSocket.open())
        {
            if(!m_serverSocket.bind(port))
            {
                return false;
            }
            return true;
        }
        return false;
    }
    void startServer()
    {
        m_mainThread.start(this);
    }
    void stopServer()
    {
        m_mainThread.cancel();
    }
public:
	void run()
    {
        while (1) 
        {
            char buf[64] = { 0 };
            sint32 ret=m_serverSocket.readData(buf, sizeof(buf)-1,500);
            if (ret>0)
            {
                TRACE_DBG_CLASS("server recv:[%s]\n",buf);
                char buf[]="hello udp client!";
                m_serverSocket.writeData(buf, sizeof(buf)); 
            }
        }
	}
private:
    Thread m_mainThread;
    UdpSocket m_serverSocket;
};

void TestUdp(void)
{
	/* 启动服务线程 */
	UdpServer server;
    if(!server.initServer(UDP_PORT))
    {
        TRACE_ERR("init UDP server failed.\n");
		return;
    }
    server.startServer();

	/* 等待服务端启动完毕 */
	sleep(2);

	/* 客户端建立连接 */
	UdpSocket client;
	client.open();
	client.bind(UDP_PORT+1);
    client.connectToHost(UDP_PORT,"127.0.0.1");
	while(1)
	{
		char sendBuf[]="hello udp server!";
        TRACE_DBG("client send msg:%s\n",sendBuf);
		client.writeData(sendBuf, sizeof(sendBuf));
        sleep(2);
        char buf[64]={0};
        int ret=client.readData(buf, sizeof(buf), 1000);
        if (ret>0)
        {
            TRACE_YELLOW("client get respond:[%s]\n",buf);
        }
	}
    server.stopServer();
}

